<template>
  <div class="chart-container">
    <h1>数据图表</h1>
    <div class="charts-wrapper">
      <div ref="lineChartRef" class="chart"></div>
      <div ref="pieChartRef" class="chart"></div>
      <div ref="barChartRef" class="chart"></div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, onUnmounted, ref} from 'vue';
import * as echarts from 'echarts';
import {lineChartOption} from "@/views/Test/components/Test3/lineChartData";
import {pieChartOption} from "@/views/Test/components/Test3/pieChartData";
import {barChartOption} from "@/views/Test/components/Test3/barChartData";

const lineChartRef = ref<HTMLElement | null>(null);
const pieChartRef = ref<HTMLElement | null>(null);
const barChartRef = ref<HTMLElement | null>(null)

let lineChartInstance: echarts.ECharts | null = null;
let pieChartInstance: echarts.ECharts | null = null;
let barChartInstance: echarts.ECharts | null = null


const initCharts = () => {
  if (!lineChartRef.value ||
      !pieChartRef.value ||
      !barChartRef.value) return;

  // 初始化折线图
  lineChartInstance = echarts.init(lineChartRef.value);
  // 初始化饼图
  pieChartInstance = echarts.init(pieChartRef.value);

  barChartInstance = echarts.init(barChartRef.value)

  // 设置图表配置
  lineChartInstance.setOption(lineChartOption);
  pieChartInstance.setOption(pieChartOption);
  barChartInstance.setOption(barChartOption);

  // 响应式调整
  const resizeCharts = () => {
    lineChartInstance?.resize();
    pieChartInstance?.resize();
  };
  window.addEventListener('resize', resizeCharts);

  // 在组件卸载时移除监听器
  onUnmounted(() => {
    window.removeEventListener('resize', resizeCharts);
    lineChartInstance?.dispose();
    pieChartInstance?.dispose();
  });
};

onMounted(() => {
  initCharts();
});
</script>

<style scoped>
.chart-container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

h1 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.charts-wrapper {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: center;
}

.chart {
  width: 100%;
  min-width: 400px;
  height: 400px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

@media (max-width: 900px) {
  .charts-wrapper {
    flex-direction: column;
  }

  .chart {
    min-width: 100%;
  }
}
</style>